package com.iflytek.cosmo.ocr.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * MVC配置自定义
 * 
 * @author ljhan2
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


	/**
	 * settingProperties
	 */
	@Autowired
	private VersionSettingProperties settingProperties;

	/**
	 * Cors支持
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*").allowedMethods("HEAD", "GET", "PUT", "POST", "PATCH", "DELETE")
				.allowedHeaders("*").allowCredentials(true);
	}


    /**
     * 增加默认首页配置
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }

	/**
	 * 添加软件库静态发布
	 * @param registry registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 路径的最后一个/必须存在，否则会导致静态发布不生效
		String packageMappingBaseUrl = settingProperties.getPackageMappingBaseUrl();
		String urlPath = null;
		if (packageMappingBaseUrl.startsWith("/")) {
			urlPath = packageMappingBaseUrl;
		} else {
			urlPath = "/" + packageMappingBaseUrl;
		}
		if (urlPath.endsWith("/")) {
			urlPath = urlPath + "**";
		} else {
			urlPath = urlPath + "/**";
		}

		String packageStoreHome = settingProperties.getPackageStoreHome();
		String fileUrl = null;
		if (packageStoreHome.endsWith("/")) {
			fileUrl = packageStoreHome;
		} else {
			fileUrl = packageStoreHome + "/";
		}
		registry.addResourceHandler(urlPath).addResourceLocations("file:" + fileUrl);
		super.addResourceHandlers(registry);
	}
}
